// highlightHandler.js
import * as Cesium from 'cesium';

export function addHighlightHandler(viewer) {
  // 测试深度
  viewer.scene.globe.depthTestAgainstTerrain = true;

  // 高亮交互操作
  const highlighted = {
    feature: undefined,
    originalMaterial: undefined,
    originalOutlineColor: undefined
  };

  const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  handler.setInputAction(function onMouseMove(movement) {
    // 恢复之前高亮的要素
    if (Cesium.defined(highlighted.feature)) {
      highlighted.feature.polygon.material = highlighted.originalMaterial;
      highlighted.feature.polygon.outlineColor = highlighted.originalOutlineColor;
    }

    // 拾取新要素
    const pickedFeature = viewer.scene.pick(movement.endPosition);
    if (!Cesium.defined(pickedFeature)) {
      highlighted.feature = undefined;
      return;
    }

    const entity = pickedFeature.id;
    if (!Cesium.defined(entity) || !entity.polygon) {
      highlighted.feature = undefined;
      return;
    }

    // 高亮新要素
    highlighted.feature = entity;
    highlighted.originalMaterial = entity.polygon.material;
    highlighted.originalOutlineColor = entity.polygon.outlineColor;

    entity.polygon.material = Cesium.Color.YELLOW.withAlpha(0.2);
    entity.polygon.outlineColor = Cesium.Color.RED;
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
}
